package tools.settings.xml;

import org.xml.sax.*;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.*;
import java.util.*;

import tools.settings.*;

/**
 *
 * @author Lynne Vandousselaere
 */
public class XMLSettingsReader implements SettingsReader {

    @Override
    public Map<String, Map<String, String>> getSettings(File xmlfile)
            throws SettingsReaderException {
        try {
            return parseXML(xmlfile);
        } catch (Exception ex) {
            throw new SettingsReaderException(ex);
        }
    }

    /**
     * A map containing all XML elements, with key=name of the element,
     * and value= a list of parameters as (name,value)-sets.
     *
     * <p> Currently used parameternames are: "xmlns", "type", "qname" and
     * "value".</p>
     *
     * @param file
     *      the XML input file.
     * @return A map containing all XML elements, with key=name of the element,
     * and value= a list of parameters as (name,value)-sets.
     * @throws org.xml.sax.SAXException
     * @throws java.io.IOException
     * @throws tools.settings.FetchException
     */
    private Map<String, Map<String, String>> parseXML(File file)
            throws SAXException, IOException, SettingsReaderException {
        XMLReader xr = XMLReaderFactory.createXMLReader();
        SimpleSAXHandler handler = new SimpleSAXHandler();
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);

        xr.parse(new InputSource(new FileReader(file)));

        handler.checkErrors();
        return handler.getElements();
    }
}
